package com.postracker.postracker.io.txt;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.postracker.postracker.io.ListOfRows;

public class StatementsFile implements ListOfRows {

	private static final String END_OF_STATEMENT = ";";
	private ListOfRows rowFile;

	protected StatementsFile(ListOfRows rowFile) {
		this.rowFile = rowFile;
	}

	@Override
	public List<String> getRows() {
		String stmts = concatNotEmptyRows();
		List<String> statements = splitStatementsRemovingEoS(stmts);
		return removeEmptyStmts(statements);
	}

	private String concatNotEmptyRows() {
		StringBuilder sb = new StringBuilder();
		for (String row : rowFile.getRows()) {
			if (StringUtils.isNotEmpty(row)) {
				sb.append(row);
			}
		}
		return sb.toString();
	}

	private List<String> splitStatementsRemovingEoS(String allStmts) {
		String[] split = allStmts.split(END_OF_STATEMENT);
		return Arrays.asList(split);
	}

	private List<String> removeEmptyStmts(List<String> statements) {
		List<String> validStmts = new ArrayList<String>();
		for (String stmt : statements) {
			if (StringUtils.isNotEmpty(stmt)) {
				validStmts.add(stmt);
			}
		}
		return validStmts;
	}
}
